package com.wyh.cloud.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.wyh.cloud.handler.CustomerBlockHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import pojo.CommonResult;
import pojo.Payment;

/**
 * @author wyh
 * @version 1.0
 * @date 2021/11/26 9:06
 */
@RestController
@Slf4j
public class RateLimitController {

    @GetMapping(value = "/byResource")
    @SentinelResource(value = "byResource", blockHandler = "blockHandler")
    public CommonResult byResource() {
        Payment payment = new Payment(2001, UUID.randomUUID().toString());
        log.info(200 + "  byResource访问正常 " + payment);
        return new CommonResult(200, " byResource访问正常 ", payment);
    }

    public CommonResult blockHandler(BlockException exception) {
        String serial = UUID.randomUUID().toString();
        log.warn(444 + "访问异常 " + exception + "---" + serial);
        return new CommonResult(444, "访问异常 " + exception + "---" + serial);
    }

    @GetMapping(value = "/rateLimit/byUrl")
    @SentinelResource(value = "byUrl")
    public CommonResult byUrl() {
        Payment payment = new Payment(2002, UUID.randomUUID().toString());
        log.info(200 + "  byUrl访问正常 " + payment);
        return new CommonResult(200, " byUrl访问正常 ", payment);
    }


    @GetMapping(value = "/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = {CustomerBlockHandler.class},
            blockHandler = "HandlerException2")
    public CommonResult customerBlockHandler() {
        Payment payment = new Payment(2003, UUID.randomUUID().toString());
        log.info(200 + "  byUrl访问正常 " + payment);
        return new CommonResult(200, " customerBlockHandler访问正常 ", payment);
    }
}
